﻿using NHibernate.Criterion;
using Online_Course.Core;
using Online_Course.Domain;
using Online_Course.Service;
using Online_Course.Web.Apps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Online_Course.Web.Controllers
{
    public class CourseController : Controller
    {
        //
        // GET: /Course/
        #region 列表
        public ActionResult Index(int pageIndex = 1, string qryUserName = "")
        {
            //满足条件记录总数
            int count = 0;
            IList<Order> listcourse = new List<Order>() { new Order("ID", true) };
            IList<Course> list = Container.Instance.Resolve<ICourseService>().Query(new List<ICriterion>() { new LikeExpression("Name", "%" + qryUserName + "%") }, listcourse, pageIndex, PagerHelper.PageSize, out count);
            //转换为PageList集合
            PageList<Course> pageList = list.ToPageList<Course>(
                pageIndex
                , PagerHelper.PageSize
                , count);
            return View(pageList);//用pageList集合填充页面。
        }
        #endregion

        #region 教师列表
        public ActionResult TeacherIndex(int pageIndex = 1, string qryUserName = "")
        {
            //满足条件记录总数
            int count = 0;
            string Username = AppHelper.LoginedUser.Name;//获取当前登录用户的用户名
            IList<Course> Clist = Container.Instance.Resolve<ICourseService>().GetAll();
            IList<Order> listcourse = new List<Order>() { new Order("ID", true) };
            Course[] list = new Course[20];
            for(int Count=0;Count<Clist.Count;Count++)
            {
                if(Clist[Count].TeacherList[0].Name==Username)
                {
                    list[Count] = Clist[Count];
                }
            }
            //转换为PageList集合
            PageList<Course> pageList = list.ToPageList<Course>(
                pageIndex
                , PagerHelper.PageSize
                , count);
            return View(pageList);//用pageList集合填充页面。
        }
        #endregion

        #region 学生选课列表 
        public ActionResult StudentIndex(int pageIndex = 1, string qryUserName = "")
        {
            //满足条件记录总数
            int count = 0;
            //IList<SysRole> RoleList = AppHelper.LoginedUser.SysRoleList;
            IList<Order> listcourse = new List<Order>() { new Order("ID", true) };
            IList<Course> list = Container.Instance.Resolve<ICourseService>().Query(new List<ICriterion>() { new LikeExpression("Name", "%" + qryUserName + "%") }, listcourse, pageIndex, PagerHelper.PageSize, out count);
            //转换为PageList集合
             PageList<Course> pageList = list.ToPageList<Course>(
                pageIndex
                , PagerHelper.PageSize
                , count);
            return View(pageList);//用pageList集合填充页面。
        }

        [HttpPost]

        public string studentIndex(int id)
        {
            Course Cou = Container.Instance.Resolve<ICourseService>().GetEntity(id);
            if(Cou.ChoosePeople>=Cou.Maxpeople)
            {
                return "本课程已经选满，请重新选择！";
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region 新增
        public ActionResult Create()
        {
            Course course = new Course();
            //获取所有课程
            //IList<Course> lst = Container.Instance.Resolve<ICourseService>().GetAll();
            //IList<SelectListItem> lstcourse = new List<SelectListItem>();
            //获取教师信息
            IList<SelectListItem> TeacherList = new List<SelectListItem>();
            IList<Teacher> teacherList = Container.Instance.Resolve<ITeacherService>().GetAll();
            foreach(Teacher c in teacherList)
            {
                TeacherList.Add(new SelectListItem() { Value = c.ID.ToString(), Text = c.Name });
            }
            ViewBag.TeacherList = TeacherList;
            return View(course);
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="course">用户实体</param>
        /// <param name="roleIDs">角色IDS</param>
        /// <param name="statusValue">用户状态</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(Course course, string roleIDs = "", string statusValue = "0",string TeacherId="0")
        {
            try
            {
                //拆分课程字符串；
                string[] arrIds = roleIDs.Split(',');
                IList<Teacher> teacherList = new List<Teacher>();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //根据ID查找课程信息
                        teacherList.Add(Container.Instance.Resolve<ITeacherService>().GetEntity(Int32.Parse(n)));
                    }
                }
                //构建实体
                course.TeacherList = teacherList;
                //保存到数据库中
                Container.Instance.Resolve<ICourseService>().Add(course);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            //根据ID 查询要修改的实体
            Course entity = Container.Instance.Resolve<ICourseService>().GetEntity(id);
            //查询所有课程信息；
            IList<Course> courseList = Container.Instance.Resolve<ICourseService>().GetAll();
            //查询所有教师
            IList<Teacher> teacherList = Container.Instance.Resolve<ITeacherService>().GetAll();
            IList<SelectListItem> teacherlist = new List<SelectListItem>();
            foreach (Teacher r in teacherList)
            {
                bool isExist = false;
                //查找是否存在该用户的角色列表中；
                int count = entity.TeacherList.Where(o => o.ID == r.ID).Count();
                //如果>0，则要被选中，否则不勾选；
                if (count > 0)
                { isExist = true; }
                SelectListItem sli = new SelectListItem() { Text = r.Name, Value = r.ID.ToString(), Selected = isExist };
                teacherlist.Add(sli);
            }
            ViewBag.teacherlist = teacherlist;
            //TeacherList.Insert(0, new Teacher() { ID = 0, Name = "===请选择===", TeacherCode = "000" });

            return View(entity);
        }

        [HttpPost]
        public ActionResult Edit(int id, Course entity, string roleIDs = "", string statusValue = "0",string TeacherId="0")
        {

            //根据ID获取需要修改的课程；
            Course course = Container.Instance.Resolve<ICourseService>().GetEntity(id);
            try
            {
                string[] arrIds = roleIDs.Split(',');
                IList<Teacher> teacherList = new List<Teacher>();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //查询当前ID的角色，并添加到角色列表中
                        teacherList.Add(Container.Instance.Resolve<ITeacherService>().GetEntity(Int32.Parse(n)));
                    }
                }
                //构建用户实体
                course.Name = entity.Name;
                course.CourseCode = entity.CourseCode;
                course.Remark = entity.Remark;
                course.Maxpeople = entity.Maxpeople;
                course.TeacherList = teacherList;
                //修改实体，保存
                Container.Instance.Resolve<ICourseService>().Update(course);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 操作

        public ActionResult SwitchStatus(int id, string type)
        {
            Course course = Container.Instance.Resolve<ICourseService>().GetEntity(id);
            if (type.Equals("Active"))
            {
                course.IsActive = 1;
            }
            else if (type.Equals("Enabled"))
            {
                course.IsActive = 0;
            }
            Container.Instance.Resolve<ICourseService>().Update(course);
            return RedirectToAction("Index");//跳转到列表页面
        }
        //public ActionResult SwitchStatus(int id, string type)
        //{
        //    Course course = Container.Instance.Resolve<ICourseService>().GetEntity(id);
        //    Container.Instance.Resolve<ICourseService>().Update(course);
        //    return RedirectToAction("Index");//跳转到列表页面
        //}

        public ActionResult Delete(int id)
        {
            Course course = Container.Instance.Resolve<ICourseService>().GetEntity(id);
            Container.Instance.Resolve<ICourseService>().Delete(course);
            return RedirectToAction("Index");
        }

        public ActionResult Choose(int id)
        {
            int Sid = AppHelper.LoginedUser.ID;
            Student_Course course = new Student_Course();
            Course cou = Container.Instance.Resolve<ICourseService>().GetEntity(id);//获取当前课程的信息
            SysUser user = Container.Instance.Resolve<ISysUserService>().GetEntity(Sid);//获取当前登陆人的信息
            IList<Student> lst = Container.Instance.Resolve<IStudentService>().Query(new List<ICriterion>() { Expression.Eq("Name", user.Name) });
            Student stu = Container.Instance.Resolve<IStudentService>().GetEntity(lst[0].ID);
            //构建实体
            course.Course = cou;
            course.Student = stu;
            course.CourseName = course.Course.Name;
            course.StudentName = course.Student.Name;
            course.TeacherName = cou.TeacherList[0].Name;
            //保存到数据库
            Container.Instance.Resolve<IStudent_CourseService>().Add(course);
            Container.Instance.Resolve<ICourseService>().Update (cou);
            return RedirectToAction("StudentIndex");
        }
        #endregion
	}
}